package main

import(
  "strconv"
  "time"
  "context"
  "sync"
  "github.com/kitech/php-go/phpgo"
)

type SyncMutex struct{
    Key  string
    Unlocked bool
}

var MutexList map[string]*sync.Mutex = map[string]*sync.Mutex{}

func NewSyncMutex() *SyncMutex{
    return &SyncMutex{Unlocked:true}
}

func (this *SyncMutex) Lock(waitRaw int) bool{
   wait,_ := time.ParseDuration(strconv.Itoa(waitRaw)+"s")
   ctx, cancel := context.WithCancel(context.Background())
   c := make(chan bool)
   go mutexLock(this.Key, ctx, c)
   defer cancel()
   select{
     case <- time.After(wait):
        return false
     case <-c:
        this.Unlocked = false
        return true
   }
}

func (this *SyncMutex) SetKey(key string){
    _, ok := MutexList[key]
    if !ok{
        var mutex sync.Mutex
        MutexList[key] = &mutex
    }
    this.Key = key
}

func mutexLock(key string, ctx context.Context, c chan bool){
  MutexList[key].Lock()
  c<-true
}

func (this *SyncMutex) Unlock() bool{
  if !this.Unlocked{
      MutexList[this.Key].Unlock()
      return true
  }
  return false
}

func init(){
  phpgo.InitExtension("sync","1.0.0")
  phpgo.AddClass("SyncMutex", NewSyncMutex)
}

func main(){
  panic("error")
}
